package com.mju.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mju.dao.OrderDao;
import com.mju.dao.OrderItemDao;
import com.mju.pojo.*;
import com.mju.service.*;
import com.mju.service.ex.InsertException;
import com.mju.vo.CartVO;
import com.mju.vo.OrderVo;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderItemDao orderItemDao;

    // 需要调用收货地址业务层的getByAid方法
    @Autowired
    private IAddressService addressService;

    // 需要调用购物车业务层的getVOByCids方法
    @Autowired
    private ICartService cartService;

    // 需要调用用户业务层的getByUid方法
    @Autowired
    private IUserService userService;

    @Autowired
    private IProductService productService;

    @Override
    public Order createOrder(Integer aid, Integer[] cids, Integer uid, String username) {
        //返回的列表中的对象都是即将下单的
        List<CartVO> list = cartService.getVOByCids(uid, cids);

        // 计算本订单中的商品总价
        long totalPrice = 0L;
        for (CartVO cartVO : list) {
            totalPrice += cartVO.getRealPrice()*cartVO.getNum();

        }
        Address address = addressService.getByAid(aid, uid);
        Order order = new Order();
        order.setUid(uid);

        //封装收货地址
        order.setAid(address.getId());
        order.setRecvName(address.getName());
        order.setRecvPhone(address.getPhone());
        order.setRecvProvince(address.getProvinceName());
        order.setRecvCity(address.getCityName());
        order.setRecvArea(address.getAreaName());
        order.setRecvAddress(address.getAddress());

        //封装创建时间,支付状态和总价
        order.setOrderTime(new Date());
        order.setStatus(0); // 0: 未支付
        order.setTotalPrice(totalPrice);

        //封装四个日志
        order.setCreatedUser(username);
        order.setCreatedTime(new Date());
        order.setModifiedUser(username);
        order.setModifiedTime(new Date());

        // 插入订单数据
        int rows = orderDao.insert(order);
        if(rows != 1) {
            throw new InsertException("插入数据时产生未知的异常");
        }

        // 插入订单的所有商品的详细数据
        for(CartVO cartVO: list) {
            // 创建订单项
            OrderItem orderItem = new OrderItem();
            // 封装数据
            orderItem.setOid(order.getOid()); // 主键自增

            orderItem.setPid(cartVO.getPid());
            orderItem.setTitle(cartVO.getTitle());
            orderItem.setImage(cartVO.getImage());
            orderItem.setPrice(cartVO.getRealPrice());
            orderItem.setNum(cartVO.getNum());

            orderItem.setCreatedUser(username);
            orderItem.setCreatedTime(new Date());
            orderItem.setModifiedUser(username);
            orderItem.setModifiedTime(new Date());

            rows = orderItemDao.insert(orderItem);
            if (rows != 1) {
                throw new InsertException("插入数据时产生未知的异常");
            }
        }
        return order;
    }

    @Override
    public Integer createOrderItem(Integer oid, Integer cid, Integer num, String username) {
        //根据cid查询订单获取pid
        Cart cart = cartService.queryCartByCid(cid);

        //取出pid的值
        Integer pid = cart.getPid();

        //根据pid查询商品信息
        Product product = productService.selectById(pid);

        //创建一个用于向持久层传输的OrderItem实体类对象
        OrderItem orderItem = new OrderItem();

        //补全orderItem对象的空白字段
        orderItem.setOid(oid);
        orderItem.setPid(pid);
        orderItem.setTitle(product.getTitle());
        orderItem.setImage(product.getImage());
        orderItem.setPrice(product.getPrice());
        orderItem.setNum(num);
        Date createdTime = new Date();
        orderItem.setCreatedUser(username);
        orderItem.setCreatedTime(createdTime);
        orderItem.setModifiedUser(username);
        orderItem.setModifiedTime(createdTime);

        //调用持久层进行插入
        int result = orderItemDao.insert(orderItem);

        if (result == 0){
            throw new InsertException("服务器出现错误，创建订单失败");
        }

        return result;
    }

    @Override
    public Boolean updateStatusByOid(Integer oid) {
        Order order = orderDao.selectById(oid);
        order.setStatus(1);
        return orderDao.updateById(order)>0;
    }



    @Override
    public List<OrderVo> queryOrderVoByOid(Integer oid) {
        List<OrderVo> orderVos = orderDao.queryOrderVoByOid(oid);
        for (OrderVo vo: orderVos) {
            //根据每个订单的oid查询地址信息
            Address address = addressService.queryAddressByAid(vo.getAid());
            //补全OrderVo值对象中的空白字段
            vo.setZip(address.getZip());
            vo.setPhone(address.getPhone());
            vo.setProvinceName(address.getProvinceName());
            vo.setCityName(address.getCityName());
            vo.setAreaName(address.getAreaName());
            vo.setAddress(address.getAddress());
        }
        return orderVos;
    }

    @Override
    public List<OrderVo> queryOrderVoByUid(Integer uid) {
        List<OrderVo> orderVos = orderDao.queryOrderVoByOid(uid);
        for (OrderVo vo: orderVos) {
            //根据每个订单的oid查询地址信息
            Address address = addressService.queryAddressByAid(vo.getAid());
            //补全OrderVo值对象中的空白字段
            vo.setZip(address.getZip());
            vo.setPhone(address.getPhone());
            vo.setProvinceName(address.getProvinceName());
            vo.setCityName(address.getCityName());
            vo.setAreaName(address.getAreaName());
            vo.setAddress(address.getAddress());
        }
        return orderVos;
    }

    @Override
    public IPage<Order> queryAllOrderInfo(Integer currentPage, Integer pageSize) {
        IPage page = new Page<>(currentPage, pageSize);
        orderDao.selectPage(page,null);
        return page;
    }

    @Override
    public IPage<Order> conQueryAllOrderInfo(Integer currentPage, Integer pageSize, Order order) {
        IPage page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<Order> lwq=new LambdaQueryWrapper<>();
        lwq.eq(!Objects.isNull(order.getOid()), Order::getOid, order.getOid());
        lwq.eq(!Objects.isNull(order.getUid()), Order::getUid, order.getUid());
        lwq.like(Strings.isNotEmpty(order.getRecvName()),Order::getRecvName,order.getRecvName());
        lwq.eq(Strings.isNotEmpty(order.getRecvPhone()),Order::getRecvPhone,order.getRecvPhone());
        lwq.eq(!Objects.isNull(order.getStatus()), Order::getStatus, order.getStatus());
        orderDao.selectPage(page,lwq);
        return page;
    }
}
